package gui.admin.ticketsinfor;

import database.TableDatabaseUsage;
import gui.admin.mtm.ATM1;
import gui.admin.mtm.OTM;
import info.UserOrder;
import messages.flight.DeFLliInfoResponseMessage;
import messages.flight.DeFliInfoRequestMessage;
import messages.order.DeOrderInfoRequestMessage;
import messages.order.DeOrderInfoResponeMessage;
import messages.order.QueryOrderInfoRequestMessage;
import messages.order.QueryOrderInfoResponeMessage;
import server.MessageServer;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

public class Order_Tickets extends JFrame {
    private JTable jTable;
    private String order_id;
    private UserOrder cacheOrder = new UserOrder();
    public Order_Tickets(){
        setTitle("订单管理");
        setSize(700, 500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        UI();
        setResizable(false);
        setVisible(true);
    }

    private void UI() {
        jTable = new JTable(OTM.getInstance());
        //头部欢迎文字
        JPanel jp = new JPanel();
        jp.setBounds(130, 30, 500, 60);
        JLabel jL = new JLabel("欢迎使用订单管理系统！");

        //创建文字对象

        jL.setFont(new Font("Serif", Font.BOLD, 33));
        jL.setForeground(Color.darkGray);
        jp.add(jL);
        this.add(jp);
        JButton btn1 = new JButton("查询");
        JButton btn2 = new JButton("查看订单");
        JButton btn3 = new JButton("删除订单");
        JPanel panel = new JPanel();


        //查询按钮
        btn1.setBounds(280, 100, 90, 35);


        this.getContentPane().add(btn1);
        btn2.setBounds(50,400,125,35);
        btn2.addActionListener(e -> {
            System.out.println("查看订单按钮被点击了");
            int selectedRow=jTable.getSelectedRow();
            if(selectedRow!=-1) {
                String OrderNOed = (String) jTable.getValueAt(selectedRow, 0);
                String IDNOed = (String) jTable.getValueAt(selectedRow, 1);
                String Flighted = (String) jTable.getValueAt(selectedRow, 2);
                Date Fdated = (Date) jTable.getValueAt(selectedRow, 3);
                String Fclassed = (String) jTable.getValueAt(selectedRow, 4);
                Float Discounted = (Float) jTable.getValueAt(selectedRow, 5);
                String OrderStated = (String) jTable.getValueAt(selectedRow, 6);
                Timestamp OrderTimed = (Timestamp) jTable.getValueAt(selectedRow, 7);

                sendQueryOrderInfoMsg(OrderNOed);
                System.out.println("你选择订单为" + OrderNOed);
                cacheOrder.setOrderNO(OrderNOed);
                cacheOrder.setIDNO(IDNOed);
                cacheOrder.setFlight(Flighted);
                cacheOrder.setFdate(Fdated);
                cacheOrder.setFclass(Fclassed);
                cacheOrder.setDiscount(Discounted);
                cacheOrder.setOrderState(OrderStated);
                cacheOrder.setOrderTime(OrderTimed);
                new QueryOrderInfoForm();
            }else{
                JOptionPane.showMessageDialog(null,"请选择一行进行查看！");
            }
        });
        btn3.setBounds(510,400,125,35);
        btn3.addActionListener(e -> {
            System.out.println("删除订单按钮被点击了");
            int selectedRow=jTable.getSelectedRow();
            if(selectedRow!=-1){
                int response = JOptionPane.showConfirmDialog(null, "确认删除吗！", "删除确认", JOptionPane.YES_NO_OPTION);
                String OrderIDed = (String) jTable.getValueAt(selectedRow,0);

                System.out.println("你删除订单为"+OrderIDed);
                // 根据用户选择执行相应操作
                if (response == JOptionPane.YES_OPTION) {
                    // 用户选择了“是”，执行删除操作
                    System.out.println("用户确认删除");
                    JOptionPane.showMessageDialog(null, "删除成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
                    sendDeleteOrdersInfoMsg(OrderIDed);
                    OTM.getInstance().userOrders=TableDatabaseUsage.getInstance().getUserOrderList();
                    jTable.updateUI();
                    // 在这里添加删除逻辑
                } else if (response == JOptionPane.NO_OPTION) {
                    // 用户选择了“否”，取消删除操作
                    System.out.println("用户取消删除");
                    JOptionPane.showMessageDialog(null, "您已取消删除！", "操作失败", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // 用户关闭了对话框或点击了其他按钮（如果有）
                    System.out.println("用户关闭了对话框或点击了其他按钮");
                }

            }else {
                JOptionPane.showMessageDialog(null, "请选择一行进行删除！");
            }
        });
        this.getContentPane().add(btn2);
        this.getContentPane().add(btn3);
        //订单号
        JLabel OrderLabel = new JLabel("订单号:");
        OrderLabel.setBounds(50, 100, 100, 35);

        JTextField fieldOrdNum = new JTextField("输入订单号");


        //监听事件：
        fieldOrdNum.addFocusListener(new FocusListener() {

            @Override
            public void focusLost(FocusEvent e) {
                //失去焦点时，用户尚未在文本框输入任何内容，依旧显示提示文字
                if (fieldOrdNum.getText().equals("")) {
                    fieldOrdNum.setForeground(Color.gray);
                    fieldOrdNum.setText("输入订单号");

                }

            }

            @Override
            public void focusGained(FocusEvent e) {
                //得到焦点时，文本框的提示文字和创建该对象时的提示文字一样，说明用户正要输入内容
                if (fieldOrdNum.getText().equals("输入订单号")) {
                    fieldOrdNum.setText("");
                    fieldOrdNum.setForeground(Color.black);
                }

            }
        });

        fieldOrdNum.setBounds(120, 100, 150, 35);
        btn1.addActionListener(e -> {
            System.out.println("查询按钮被点击了！");
            if(!fieldOrdNum.getText().equals("")&&!fieldOrdNum.getText().equals("输入订单号")){
                order_id=fieldOrdNum.getText();
                OTM.getInstance().userOrders= TableDatabaseUsage.getInstance().getUserOrderList1(order_id);
                fieldOrdNum.setText("输入订单号");
                jTable.updateUI();

            }

        });
        this.getContentPane().add(OrderLabel);
        this.getContentPane().add(fieldOrdNum);
        this.getContentPane().add(panel);

        //表格

        JScrollPane scroll = new JScrollPane(jTable);

        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scroll.setPreferredSize(new Dimension(620, 200));
        jTable.setBackground(Color.white);
        jTable.setRowHeight(40);

        jTable.setGridColor(Color.pink);
        jTable.setSelectionBackground(Color.orange);
        //使表格文字居中
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();

        centerRenderer.setHorizontalAlignment(JLabel.CENTER);


        for (int i = 0; i < jTable.getColumnCount(); i++) {
            jTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);

        }


        panel.setBorder(BorderFactory.createEmptyBorder(150, 0, 0, 0));


        panel.add(scroll);
    }
    private UserOrder userOrder = new UserOrder();
    class QueryOrderInfoForm extends JFrame{
        JTextField OrderNOTextField;
        JTextField IDNOTextField;
        JTextField FlightTextField;
        JTextField FdateTextField;
        JTextField FclassTextField;
        JTextField DiscountTextField;
        JTextField OrderStateTextField;
        JTextField OrderTimeTextField;
        public QueryOrderInfoForm(){

            super("查看订单信息");
            setSize(500,500);
            setLayout(new GridLayout(9,2));
            OrderNOTextField=new JTextField(cacheOrder.getOrderNO());
            IDNOTextField=new JTextField(cacheOrder.getIDNO());
            FlightTextField=new JTextField(cacheOrder.getFlight());
            FdateTextField=new JTextField(String.valueOf(cacheOrder.getFdate()));
            FclassTextField=new JTextField(cacheOrder.getFclass());
            DiscountTextField=new JTextField(String.valueOf(cacheOrder.getDiscount()));
            OrderStateTextField=new JTextField(cacheOrder.getOrderState());
            OrderTimeTextField=new JTextField(String.valueOf(cacheOrder.getOrderTime()));
            OrderNOTextField.setEditable(false);
            IDNOTextField.setEditable(false);
            FlightTextField.setEditable(false);
            FdateTextField.setEditable(false);
            FclassTextField.setEditable(false);
            DiscountTextField.setEditable(false);
            OrderStateTextField.setEditable(false);
            OrderTimeTextField.setEditable(false);
            JButton BackInfoButton = new JButton("返回");
            BackInfoButton.addActionListener(e -> {
               dispose();
            });
            JLabel l1 = new JLabel("订单号：");
            JLabel l2 = new JLabel("身份证号：");
            JLabel l3 = new JLabel("航班：");
            JLabel l4 = new JLabel("航班日期：");
            JLabel l5 = new JLabel("舱位：");
            JLabel l6 = new JLabel("折扣：");
            JLabel l7 = new JLabel("订单状态：");
            JLabel l8 = new JLabel("订票时间：");

            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);
            l4.setHorizontalAlignment(JLabel.CENTER);
            l5.setHorizontalAlignment(JLabel.CENTER);
            l6.setHorizontalAlignment(JLabel.CENTER);
            l7.setHorizontalAlignment(JLabel.CENTER);
            l8.setHorizontalAlignment(JLabel.CENTER);

            add(l1);
            add(OrderNOTextField);
            add(l2);
            add(IDNOTextField);
            add(l3);
            add(FlightTextField);
            add(l4);
            add(FdateTextField);
            add(l5);
            add(FclassTextField);
            add(l6);
            add(DiscountTextField);
            add(l7);
            add(OrderStateTextField);
            add(l8);
            add(OrderTimeTextField);

            add(new JLabel(""));
            add(BackInfoButton);

            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);
        }
    }


    public boolean sendQueryOrderInfoMsg(String OldOrderId){
        QueryOrderInfoRequestMessage queryOrderInfoRequestMessage = new QueryOrderInfoRequestMessage();
        QueryOrderInfoResponeMessage queryOrderInfoResponeMessage;
        queryOrderInfoRequestMessage.setOldOrderId(OldOrderId);

        try {
            MessageServer.getInstance().getOos().writeObject(queryOrderInfoRequestMessage);
            System.out.println("客户端发送请求成功！"+queryOrderInfoRequestMessage);
            queryOrderInfoResponeMessage = (QueryOrderInfoResponeMessage) MessageServer.getInstance().
                    getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！"+queryOrderInfoResponeMessage);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
    private boolean sendDeleteOrdersInfoMsg(String OldOrderId){
        DeOrderInfoRequestMessage deOrderInfoRequestMessage = new DeOrderInfoRequestMessage();
        DeOrderInfoResponeMessage deOrderInfoResponeMessage;
        deOrderInfoRequestMessage.setOldUserId(OldOrderId);

        try {
            MessageServer.getInstance().getOos().writeObject(deOrderInfoRequestMessage);
            System.out.println("客户端发送请求成功！"+deOrderInfoRequestMessage);
            deOrderInfoResponeMessage = (DeOrderInfoResponeMessage) MessageServer.getInstance().
                    getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！"+deOrderInfoResponeMessage);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}

